#include "meshcontroller.h"

MeshController::MeshController(MainWindow* mw, QObject *parent) :
    QObject(parent)
{
    m_canvas = new Canvas();

    connect(m_canvas, SIGNAL(draw()),
            this, SLOT(draw()));
    connect(m_canvas, SIGNAL(leftPressed(QVector2D)),
            this, SLOT(leftPressed(QVector2D)));
    connect(m_canvas, SIGNAL(leftReleased(QVector2D)),
            this, SLOT(leftReleased(QVector2D)));

    TriQuad tq(QVector2D(-2,-2), QVector2D(2,-2), QVector2D(0,2));
    tq.q(0) = TriQuad::makeQuadric(2.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    tq.q(1) = TriQuad::makeQuadric(2.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    tq.q(2) = CIRCLE;
    triQuads.append(tq);

    mw->setCanvas(m_canvas);
    mw->show();
}

void MeshController::draw()
{
    m_canvas->clear();
    for(int i = 0; i < triQuads.size(); ++i)
    {
        m_canvas->drawLines(triQuads[i].getTriangleLines());
        //m_canvas->drawLines(triQuads[i].getCurveLines());
        m_canvas->drawPoints(triQuads[i].getPointCloud());
    }
}

QPair<int, int> MeshController::buscaVertice(const QVector2D& v)
{
    float min = (v - triQuads[0].vTo2DAffine(0)).length();
    int idxTri = 0;
    int idxV = 0;

    for(int i = 0; i < triQuads.size(); ++i)
    {
        for(int j = 0; j < 3; ++j)
        {
            float l = (v - triQuads[i].vTo2DAffine(j)).length();
            if(l < min)
            {
                min = l;
                idxTri = i;
                idxV = j;
            }
        }
    }
    return qMakePair(idxTri, idxV);
}

void MeshController::leftReleased(QVector2D v)
{
    QPair<int, int> idx = buscaVertice(ini);

    triQuads[idx.first].v(idx.second) += QVector3D(v-ini,0.0);
    draw();
}

void MeshController::leftPressed(QVector2D v)
{
    ini = v;
}
